package baseFx.common;

import java.util.*;

public class EventDispatcher<T extends EventArgs> {
    private Map<String, EventListener<T>> map = new HashMap<>(8);
    private List<String> keylist = new ArrayList<>();
    private String fireKey;

    public EventDispatcher(String fireKey) {
        this.fireKey = fireKey;
    }

    public String add(int index, EventListener<T> listener) {
        String id = UUID.randomUUID().toString().replace("-", "");
        keylist.add(index, id);
        map.put(id, listener);
        return id;
    }

    public String add(EventListener<T> listener) {
        return add(keylist.size(), listener);
    }

    public void remove(String eventId) {
        if (keylist.remove(eventId)) {
            map.remove(eventId);
        }
    }

    public void fire(String key, final Object target, final T args) {
        if (fireKey.equalsIgnoreCase(key) == false) {
            throw new RuntimeException("fireKey不正确");
        }
        if (keylist.isEmpty()) {
            return;
        }
        for (String id : new ArrayList<>(keylist)) {
            EventListener<T> listener = map.get(id);
            if (listener != null) {
                args.eventId = id;
                listener.on(target, args);
            }
        }
    }

    public boolean isEmpty() {
        return keylist.isEmpty();
    }

    public void clear() {
        map.clear();
        map = null;
        keylist.clear();
        keylist = null;
        fireKey = null;
    }
}
